##############
# Results_gles.R

# This document creates all plots and tables for the 
# Results section of the GLES


#############
# Libraries
rm(list=ls())
library(ggplot2)
require(MASS)
library(rjags)
library(reshape)
library(xtable)

# Load Results and Functions
load("models_gles_rating.Rdata")
source("Model_Data_gles.R")
load("gles.Rdata")


# Models
models <- list(
                cdu.gruene.rat
               ,spd.gruene.fdp.rat  
               ,spd.gruene.linke.rat
               ,spd.fdp.rat
               )



#########################
# Figure 4



# First-difference 
df <- data.frame(cbind(as.matrix(cdu.gruene.rat)[,"diff"]
                       ,as.matrix(spd.gruene.fdp.rat)[,"diff"]
                       ,as.matrix(spd.gruene.linke.rat)[,"diff"]
                       ,as.matrix(spd.fdp.rat)[,"diff"]
))

df <- as.data.frame(t(apply(df,2,quantile,c(0.5,0.01,0.99))))
colnames(df) <- c("mid","low","high")

df$coal <- as.factor(c(1,3,4,2))
levels(df$coal) <- c("CDU-Greens","SPD-FDP","SPD-FDP-Greens","SPD-Greens-Left")

df$choice <- 3
df$type <- 2



# Weights Data
df2 <- matrix(NA, ncol=4, nrow=length(models)*2)
c <- 1
for(i in 1:length(models)){
  res <- as.matrix(models[[i]])
  mix1 <- quantile(res[,grep("gamma",colnames(res))[1]],c(0.5,0.95,0.05))
  df2[c,] <- c(mix1,1)
  mix2 <- quantile(res[,grep("gamma",colnames(res))[2]],c(0.5,0.95,0.05))
  c <- c +1; df2[c,] <- c(mix2,2)
  c <- c+1
}


df2 <-  as.data.frame(df2)  

colnames(df2)<- c("mid","low","high","choice") 

df2$coal <- as.factor(c(1,1,3,3,4,4,2,2))
levels(df2$coal) <- c("CDU-Greens","SPD-FDP","SPD-FDP-Greens","SPD-Greens-Left")
df2$type <- 1

# Combine Both

df <- rbind(df,df2)

df$type <-  as.factor(df$type)
levels(df$type) <- c("Mixing parameters","First differences") 

df$choice <-  as.factor(df$choice)
levels(df$choice) <- c("Standard","Vignette","First difference") 


# Scales

pdf("Gles-plot-joined.pdf",height=4)
ggplot(df, aes(y=mid,ymin=low,ymax=high,x=1,col=choice)) + 
  geom_pointrange(size=1,position=position_dodge(0.5))  + coord_flip() + 
  facet_grid(coal~ type,scales="free_x") +
  scale_color_grey() +  
  scale_x_continuous(name="", labels="" , breaks=1,limits=c(0,2)) + theme_bw() + 
  theme(legend.direction = "horizontal", legend.position = "top", legend.title=element_blank(), 
        strip.text.y = element_text(size=10,angle=360)) +
  scale_y_continuous(name="", breaks=c(0,0.25,0.5,0.75,1), 
                     labels=c("0","0.25","0.5","0.75","1")) 
dev.off()
